package com.uenpay.im.ui.old.activity.movement;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.image.DownloadImageTask;
import com.qiyunxin.android.http.utils.StringUtils;
import com.qiyunxin.android.http.utils.Utils;
import com.qiyunxin.android.http.view.ResizeLayout;
import com.qyx.android.message.type.PacketType;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.dynamic.Reply;
import com.uenpay.im.ui.old.activity.mycollect.CollectHandle;
import com.uenpay.im.ui.old.activity.personal.QRCodeActivity;
import com.uenpay.im.callback.IPopupWindowListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.PopupEntity;
import com.uenpay.im.panel.FacePanelByEmojiManager;
import com.uenpay.im.panel.PanelManagerInterface;
import com.uenpay.im.view.MyPopupWindow;
import com.uenpay.util.app.base.BaseActivity;

import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * @author SL
 * @created 2016-1-21 下午3:44:32
 * @copyRight http://www.qiyunxin.com
 * @function TODO
 */
public class MovementDetailActivity extends BaseActivity {

    private CollectHandle mCollectHandle = new CollectHandle();
    private MaskImageView movement_cover_iv, publish_avatar_iv;
    private TextView movement_title_tv, publish_date_tv, pubish_nick_name,
            movement_date_tv, movement_num_tv, movement_address_tv,
            movement_free_tv, movement_intro_tv, publish_area, publish_wushu;
    private MovementHandler movementHandler = new MovementHandler();
    private int movementId;
    private MovementEntity mMovementEntity = null;
    private Button apply_join_btn;
    private LinearLayout praise_layout, reply_layout, bg_reply_content_layout,
            praise_ll, reply_content;
    private View dynamic_pop_reply;
    private TextView praise_tv;
    private EditText editText;
    private View view_like_reply;
    private ReplyHandler replyHandler = null;
    private ScrollView scrollview;
    private int _praise = 0;
    private LinearLayout movement_qr_layout;
    private String pcust_id = "0";
    private String title = "", fileid, filehash, publishCustId,
            publishCustName;
    private MyPopupWindow myPopupWindow;

    private ResizeLayout mResizeLayout = null;
    private FacePanelByEmojiManager facePanelByEmojiManager = null;
    private View loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_movement_detail_layout;
    }

    @Override
    public void initView(View view) {
        movementId = getIntent().getIntExtra("movementId", 0);
        initView();
        initListener();
        getMovementDetail(movementId);
        initFacePanelView();
    }

    protected void initView() {
        mResizeLayout = (ResizeLayout) findViewById(R.id.parent);
        replyHandler = new ReplyHandler(this);
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.movement_detail));
        findViewById(R.id.title_right_iv_layout).setVisibility(View.VISIBLE);
        movement_cover_iv = (MaskImageView) findViewById(R.id.movement_cover_iv);
        publish_avatar_iv = (MaskImageView) findViewById(R.id.publish_avatar_iv);
        praise_tv = (TextView) findViewById(R.id.praise_tv);
        movement_title_tv = (TextView) findViewById(R.id.movement_title_tv);
        publish_date_tv = (TextView) findViewById(R.id.publish_date_tv);
        pubish_nick_name = (TextView) findViewById(R.id.pubish_nick_name);
        publish_area = (TextView) findViewById(R.id.publish_area);
        publish_wushu = (TextView) findViewById(R.id.publish_wushu);
        movement_date_tv = (TextView) findViewById(R.id.movement_date_tv);
        movement_num_tv = (TextView) findViewById(R.id.movement_num_tv);
        movement_address_tv = (TextView) findViewById(R.id.movement_address_tv);
        movement_free_tv = (TextView) findViewById(R.id.movement_free_tv);
        movement_intro_tv = (TextView) findViewById(R.id.movement_intro_tv);
        loading = findViewById(R.id.loading);
        apply_join_btn = (Button) findViewById(R.id.apply_join_btn);
        praise_layout = (LinearLayout) findViewById(R.id.praise_layout);
        reply_layout = (LinearLayout) findViewById(R.id.reply_layout);
        praise_ll = (LinearLayout) findViewById(R.id.praise_ll);
        bg_reply_content_layout = (LinearLayout) findViewById(R.id.bg_reply_content_layout);
        reply_content = (LinearLayout) findViewById(R.id.reply_content);
        dynamic_pop_reply = findViewById(R.id.dynamic_pop_reply);
        editText = (EditText) findViewById(R.id.editText);
        view_like_reply = findViewById(R.id.view_like_reply);
        scrollview = (ScrollView) findViewById(R.id.scrollview);
        movement_qr_layout = (LinearLayout) findViewById(R.id.movement_qr_layout);
    }

    private void initFacePanelView() {
        facePanelByEmojiManager = new FacePanelByEmojiManager(
                MovementDetailActivity.this, dynamic_pop_reply, mResizeLayout);
        facePanelByEmojiManager.initListener();
        facePanelByEmojiManager.onSendTextListener(new PanelManagerInterface.ISendTextListener() {

            @Override
            public void onSendTextContent(String editContent) {
                if (!TextUtils.isEmpty(editContent.trim())) {
                    if (editContent.length() <= 140) {
                        Utils.hideSoftKeyboard(editText);
                        dynamic_pop_reply.setVisibility(View.GONE);
                        editText.setHint("");
                        replyMovement(editContent);

                    } else {
                        IMApplication.showToast(R.string.more_text_max);
                    }
                } else {
                    IMApplication.showToast(R.string.reply_empty);
                }

            }
        });
    }

    private void initPop() {
        myPopupWindow = new MyPopupWindow(MovementDetailActivity.this,
                getPopData(), new IPopupWindowListener() {

            @Override
            public void itemClick(int index) {
                if (index == 1) {
                    Intent intent = new Intent(
                            MovementDetailActivity.this,
                            PublishMovementActivity.class);
                    intent.putExtra("movementId",
                            mMovementEntity.movementId);
                    intent.putExtra("movementTitle",
                            mMovementEntity.movementTitle);
                    intent.putExtra("movementAddress",
                            mMovementEntity.movementAddress);
                    intent.putExtra("movementCoverFileId",
                            mMovementEntity.movementCoverFileId);
                    intent.putExtra("movementCoverFileHash",
                            mMovementEntity.movementCoverFileHash);
                    intent.putExtra("movementDescription",
                            mMovementEntity.movementDescription);
                    intent.putExtra("movementFee",
                            mMovementEntity.movementFee);
                    intent.putExtra("movementPersonNum",
                            mMovementEntity.movementPersonNum);
                    intent.putExtra("movementCreateTime",
                            mMovementEntity.movementCreateTime);
                    startActivityForResult(intent, 115);
                } else if (index == 2) {
                    if (mMovementEntity.status == 1) {
                        closeOrOpenMovement(0);
                    } else {
                        closeOrOpenMovement(1);
                    }
                } else if (index == 3) {
                    // TODO
                }
            }
        });
    }

    private ArrayList<PopupEntity> getPopData() {
        ArrayList<PopupEntity> arrayList = new ArrayList<PopupEntity>();
        PopupEntity entity = new PopupEntity(-1, R.string.edit_pubish_info, 1);
        PopupEntity entity1 = null;
        if (mMovementEntity.status == HttpInvokeResultCode.RESULT_OK) {
            entity1 = new PopupEntity(-1, R.string.open_pubish_info, 2);
        } else {
            entity1 = new PopupEntity(-1, R.string.close_pubish_info, 2);
        }
        arrayList.add(entity);
        arrayList.add(entity1);
        return arrayList;
    }

    protected void initListener() {
        findViewById(R.id.back_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        finish();
                        Utils.hideSoftKeyboard(editText);
                    }
                });
        findViewById(R.id.title_right_iv_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (!publishCustId.equals(IMApplication.getCustId())) {
                            collect();
                        } else {
                            initPop();
                            if (myPopupWindow != null) {
                                myPopupWindow.show(arg0);
                            }
                        }
                    }
                });
        findViewById(R.id.publish_movement_cust_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (mMovementEntity != null) {
                            ActivityHandle.startUserDetailActivity(
                                    MovementDetailActivity.this,
                                    mMovementEntity.movementPublishCustId);
                        }
                    }
                });

        praise_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (mMovementEntity != null) {
                    praiseMovement();
                }
            }
        });
        reply_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (mMovementEntity != null) {
                    pcust_id = "0";
                    dynamic_pop_reply.setVisibility(View.VISIBLE);
                    facePanelByEmojiManager.showFacePanelView();
                    Utils.showSoftKeyboard(editText);
                }
            }
        });

        apply_join_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                loading.setVisibility(View.VISIBLE);
                movementHandler.joinMovement(movementId, new MovementHandler.IResultListener() {

                    @Override
                    public void onResult(int status, String msg) {
                        loading.setVisibility(View.GONE);
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            apply_join_btn.setText(getResources().getString(
                                    R.string.movement_joined));
                            apply_join_btn
                                    .setBackgroundResource(R.drawable.button_bg_gray);
                            apply_join_btn.setEnabled(false);
                        } else {
                            IMApplication.showToast(msg);
                        }
                    }
                });
            }
        });

        scrollview.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                Utils.hideSoftKeyboard(editText);
                editText.setHint("");
                dynamic_pop_reply.setVisibility(View.GONE);
                return false;
            }
        });

        movement_qr_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (movementId != 0) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("movement_id", movementId);
                    ActivityHandle.startActivity(MovementDetailActivity.this, QRCodeActivity.class, bundle, -1);
                }
            }
        });

        findViewById(R.id.movement_menember_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (movementId != 0) {
                            Bundle bundle = new Bundle();
                            bundle.putInt("movement_id", movementId);
                            bundle.putInt("count", mMovementEntity.movementMemberCount);
                            ActivityHandle.startActivity(MovementDetailActivity.this, SignMovementListActivity.class, bundle, -1);
                        }
                    }
                });

    }

    private void praiseMovement() {
        int op = 0;
        if (_praise == 0) {
            op = 1;
        } else {
            op = 0;
        }
        movementHandler.praiseMovement(movementId, op, new MovementHandler.IResultListener() {

            @Override
            public void onResult(int status, String msg) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    getMovementDetail(movementId);
                } else {
                    IMApplication.showToast(msg);
                }
            }
        });
    }

    private void replyMovement(String content) {
        movementHandler.replyMovement(movementId, content, pcust_id,
                new MovementHandler.IReplyMovementResultListener() {

                    @Override
                    public void onReplyMovementResult(int status, String msg,
                                                      Reply mReply) {
                        if (status == HttpInvokeResultCode.RESULT_OK
                                && mReply != null) {
                            Utils.hideSoftKeyboard(editText);
                            editText.setText("");
                            dynamic_pop_reply.setVisibility(View.GONE);
                            // Message message = myHandler.obtainMessage();
                            // message.obj = mReply;
                            // message.what = 4;
                            // myHandler.sendMessage(message);
                            getMovementDetail(movementId);
                        } else {
                            IMApplication.showToast(msg);
                        }
                    }

                });
    }

    private void getMovementDetail(int movementId) {
        loading.setVisibility(View.VISIBLE);
        movementHandler.getMovementDetial(movementId,
                new MovementHandler.IGetMovementDetialResult() {

                    @Override
                    public void onMovementDetailResult(int status, String msg,
                                                       MovementEntity movementEntity) {
                        loading.setVisibility(View.GONE);
                        if (status == HttpInvokeResultCode.RESULT_OK
                                && movementEntity != null) {
                            mMovementEntity = movementEntity;
                            new DownloadImageTask(getBaseContext()).execute(APIConfiguration
                                    .getFileDownloadPath(
                                            mMovementEntity.movementCoverFileId,
                                            mMovementEntity.movementCoverFileHash));
                            _praise = movementEntity._praise;
                            fileid = movementEntity.movementCoverFileId;
                            filehash = movementEntity.movementCoverFileHash;
                            title = movementEntity.movementTitle;
                            publishCustId = movementEntity.movementPublishCustId;
                            publishCustName = movementEntity.movementPublishNickName;
                            setRightIvIm(movementEntity._isfavorited);
                            if (!movementEntity.movementPublishCustId
                                    .equals(IMApplication.getCustId())) {
                                movement_qr_layout.setVisibility(View.GONE);
                                findViewById(R.id.movement_qr_view)
                                        .setVisibility(View.GONE);
                            }
                            movement_cover_iv.SetUrl(APIConfiguration
                                    .getFileDownloadPath(
                                            movementEntity.movementCoverFileId,
                                            movementEntity.movementCoverFileHash));
                            publish_avatar_iv.SetUrl(APIConfiguration
                                    .getAvatarUrlNormal(
                                            movementEntity.movementPublishCustId,
                                            PacketType.PERSONAL));
                            movement_title_tv
                                    .setText(movementEntity.movementTitle);
                            publish_area
                                    .setText(movementEntity.movementPublishArea);
                            publish_wushu
                                    .setText(movementEntity.movementPublishDans);
                            publish_date_tv
                                    .setText(movementEntity.movementCreateTime);
                            pubish_nick_name
                                    .setText(movementEntity.movementPublishNickName);
                            movement_date_tv
                                    .setText(movementEntity.movementStartTime);

                            movement_num_tv.setText(MessageFormat.format(
                                    getResources().getString(
                                            R.string.movement_sign),
                                    movementEntity.movementPersonNum,
                                    movementEntity.movementMemberCount));
                            movement_address_tv
                                    .setText(movementEntity.movementAddress);
                            double free = Double
                                    .valueOf(movementEntity.movementFee);
                            if (free <= 0) {
                                movement_free_tv
                                        .setText(R.string.movement_free_charge);
                            } else {
                                movement_free_tv
                                        .setText(movementEntity.movementFee
                                                + getResources()
                                                .getString(
                                                        R.string.movement_personal));
                            }

                            movement_intro_tv
                                    .setText(movementEntity.movementDescription);
                            if (movementEntity.isJoin == 0) {
                                apply_join_btn.setText(getResources()
                                        .getString(R.string.movement_not_join));
                            } else {
                                apply_join_btn.setText(getResources()
                                        .getString(R.string.movement_joined));
                                apply_join_btn
                                        .setBackgroundResource(R.drawable.button_bg_gray);
                                apply_join_btn.setEnabled(false);
                            }

                            reply_content.removeAllViews();
                            bg_reply_content_layout.setVisibility(View.GONE);
                            if (movementEntity.replylist != null
                                    && movementEntity.replylist.size() > 0) {
                                for (int i = 0; i < movementEntity.replylist
                                        .size(); i++) {
                                    // reply_list = movementEntity.replylist;
                                    View replyText = replyHandler
                                            .getReplyTextView(editText,
                                                    movementEntity.replylist
                                                            .get(i),
                                                    reply_content,
                                                    new ReplyHandler.ITextLinkListener() {

                                                        @Override
                                                        public void onTextLink(
                                                                int status,
                                                                String custId,
                                                                String pCustId) {
                                                            if (status == HttpInvokeResultCode.RESULT_OK) {
                                                                deleteReplyMovement(custId);
                                                            } else {
                                                                pcust_id = pCustId;
                                                                // showPop();
                                                                dynamic_pop_reply
                                                                        .setVisibility(View.VISIBLE);
                                                                facePanelByEmojiManager
                                                                        .showFacePanelView();
                                                                Utils.showSoftKeyboard(editText);
                                                            }
                                                        }
                                                    });
                                    reply_content.addView(replyText);
                                    reply_content.setVisibility(View.VISIBLE);
                                    bg_reply_content_layout
                                            .setVisibility(View.VISIBLE);
                                }
                            }

                            praise_tv.setText("");
                            if (movementEntity.likelist != null
                                    && movementEntity.likelist.size() > 0) {

                                replyHandler.setPraiseView(
                                        movementEntity.likelist, praise_ll,
                                        praise_tv);
                                bg_reply_content_layout
                                        .setVisibility(View.VISIBLE);
                                view_like_reply.setVisibility(View.VISIBLE);
                            } else {
                                praise_ll.setVisibility(View.GONE);
                                view_like_reply.setVisibility(View.GONE);
                            }

                            if (movementEntity._praise == 1) {
                                ((ImageView) findViewById(R.id.praise_iv))
                                        .setImageResource(R.drawable.icon_praise_selected);
                            } else {
                                ((ImageView) findViewById(R.id.praise_iv))
                                        .setImageResource(R.drawable.icon_praise_normal);
                            }
                        } else {
                            IMApplication.showToast(msg);
                        }
                    }
                });
    }

    private void deleteReplyMovement(String replyid) {
        movementHandler.deleteReplyMovement(replyid, new MovementHandler.IResultListener() {

            @Override
            public void onResult(int status, String msg) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    getMovementDetail(movementId);
                } else {
                    IMApplication.showToast(msg);
                }
            }
        });
    }

    private void collect() {
        String pic_url = StringUtils.encodeParams(APIConfiguration
                .getFileDownloadPath(fileid, filehash));
        mCollectHandle.addCollect(113, publishCustId, title, publishCustName,
                "", "", pic_url, movementId, new CollectHandle.ICollectListener() {

                    @Override
                    public void onResult(int status, String msg) {
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            ((ImageView) findViewById(R.id.title_right_iv))
                                    .setImageResource(R.drawable.icon_collected);
                        }
                    }
                });

    }

    private void setRightIvIm(int _isfavorited) {
        if (!publishCustId.equals(IMApplication.getCustId())) {
            if (_isfavorited == 1) {
                ((ImageView) findViewById(R.id.title_right_iv))
                        .setImageResource(R.drawable.icon_collected);
            } else {
                ((ImageView) findViewById(R.id.title_right_iv))
                        .setImageResource(R.drawable.icon_no_collect);
            }
        } else {
            ((ImageView) findViewById(R.id.title_right_iv))
                    .setImageResource(R.drawable.icon_more);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 115 && resultCode == -1) {
            getMovementDetail(movementId);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void closeOrOpenMovement(int status) {
        movementHandler.closeOrOpenMovement(movementId, status,
                new IMovementResultListener() {

                    @Override
                    public void onResult(int status, String msg) {
                        getMovementDetail(movementId);
                        sendBroadcast(new Intent(
                                BroadcastAction.ACTION_REFRESH_MOVEMENT));
                    }
                });
    }
}
